<script lang="ts" setup>
import type { StateType } from './types';

import { computed } from 'vue';
import { useRoute } from 'vue-router';
import { $t } from '@vben/locales';
import { Page,z } from '@vben/common-ui';
import { useTabs } from '@vben/hooks';

import { useTitle } from '@vueuse/core';
import {
  Card,
  message,
  Select,
  SelectOption,
  TabPane,
  Tabs,
} from 'ant-design-vue';
import dayjs from 'dayjs';
import { storeToRefs } from 'pinia';
import { pinyin } from 'pinyin-pro';

import { useVbenForm } from '#/adapter/form';
import { getPageInfo_selling, postPage_selling, putPage_selling } from '#/api/portal/home';
import { usePreferencesStore } from '#/store';




import { useVbenModal } from '@vben/common-ui';


const index = ref<number>(0); // 外层定义
const [Modal, formModalApi] = useVbenModal({
  fullscreenButton: false,
  footer: false,
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const values1: { id?: number } = formModalApi.getData();
      index.value = values1.id ?? 0; // 给外层的 index 赋值
      if(index.value>0){
             await onGetPage(index.value);
      }
      
    }
  },
 
});



const route = useRoute();

const { setTabTitle, closeCurrentTab } = useTabs();

// const index: any = computed(() => {
//   return route.params?.id ?? -1;
// });
const router = useRouter();

const routeMeta = router.currentRoute.value.meta;
const routeTitle = routeMeta.title.replace('管理', '');
const preferencesStore = usePreferencesStore();
const { title } = storeToRefs(preferencesStore);
// const pageTitle =
//   Number.parseInt(index.value, 10) === 0
//     ? $t('page.common.Add')+` ${routeTitle}`
//     : `No.${index.value} - `+$t('page.common.Edit')+` ${routeTitle}`;
// setTabTitle(pageTitle);
// useTitle(`${pageTitle} - ${title.value}`);

const disabled = ref(true);
const activeKey = ref('1');
const state: StateType = reactive({
  form: {
    title: '',
    discover: '',
    des: '',
    categoey:'',
   
  },
  pageThemeFiles: [],
});

const [BasicForm, BasicFormApi] = useVbenForm({
  handleSubmit: onSubmit,
  resetButtonOptions: {
    show: false,
  },
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['id'],
      },
      fieldName: 'id',
      label: 'ID',
    
    },
    {
      component: 'Input',
      defaultValue: '',
      dependencies: {
        trigger: (values) => {
          disabled.value = !values.title;
          state.form.title = values.title;
          state.form.hp = values.hp;
          state.form.cc = values.cc;
          state.form.nm = values.nm;
          state.form.images = values.images;
          state.form.url = values.url
        },
        // 随意一个字段改变时，都会触发
        triggerFields: [
          'id',
          'title',
          'hp',
          'cc',
          'nm',
          'images',
          'url'
        ],
      },
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'title',
      label: `${routeTitle} `+$t('page.common.Title'),
      rules: z.string().max(45,$t('admin.maxChars', { length: 45 })),
    },

 
    {
      component: 'InputNumber',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter')
      },
      fieldName: 'hp',
      label: `${routeTitle}hp`,
      
    },
     {
      component: 'InputNumber',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'cc',
      label: `${routeTitle}cc`,
    },
    {
      component: 'InputNumber',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'nm',
      label: `${routeTitle}nm`,
    },

    {
      component: 'Upload',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
        tips:'216px-316px'
      },
      fieldName: 'images',
      label: `${routeTitle} `+$t('page.common.Image'),
    },
     {
      component: 'Upload',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
        type:'file'
      },
      fieldName: 'url',
      label: `${routeTitle} `+$t('admin.downloadFile'),
    },
       
  ],
});


async function onSubmit() {
  const values: any = state.form;

  let response;

  if (values.id) {
    response = await putPage_selling(values);
  } else {
    delete values.id;
    response = await postPage_selling(values);
  }

  const { code, msg } = response;

  if (code === 1) {
    message.success(msg || '操作成功');
    // closeCurrentTab();
    // router.push({ name: 'Homeselling' });
    formModalApi.close();
    BasicFormApi.resetForm();
     state.form={};
  } else {
    message.error(msg || '操作失败'); 
  }
}

async function onGetPage(id: number) {
  const { data } = await getPageInfo_selling({ id });
  data.post = {
    id: data?.id ?? undefined,
    title: data?.title ?? '',
    hp: data?.hp ?? '',
    cc: data?.cc ?? '',
    nm: data?.nm ?? '',
    images: data?.images ?? [],
    url: data?.url ?? [],
  };
  state.form = data.post;
  BasicFormApi.setValues({ ...state.form});
  state.pageThemeFiles = data.pageThemeFiles;
}

// onMounted(async () => {
//   if(index.value>0){
//           await onGetPage(index.value);
//   }
  
// });
</script>

<template>
<Modal :title="state.form.name">
    <Page>
        <Card :title="`${routeTitle} `+$t('page.common.Details')">
          <BasicForm />
        </Card>
      </Page>
</Modal>
  
</template>
